package circularArray;

public class CircularArray {
    private Integer[] array ;
    private int start;
    private int end;
    //数组大小
    private int size;
    //数组中实际存了几个元素
    private int count;

    public CircularArray(int size) {
        this.array = new Integer[size];
        this.start = 0;
        this.end = 0;
        this.size = size;
        this.count = 0;
    }

    public void addFirst(int val){
        //如果数组已经满了，扩容
        if (isFull()){
            reSize(2 * size);
        }
        //start前移
        start = (start - 1 + size) % size;
        //赋值
        array[start] = val;
        count++;

    }

    public void removeFirst(){
        //检查数组中是否还有元素
        if (isEmpty()){
            throw new IllegalStateException("Array is empty");
        }

        array[start] = null;

        start = ( start + 1 ) % size;

        count--;

        if (count > 0 && count<=(size/4)){
            reSize(size / 2);
        }
    }

    public void addLast(int val){
        if (isFull()){
            reSize(2 * size);
        }

        array[end] = val;
        end = (end + 1) % size;
        count++;
    }

    public void removeLast(){
        //检查数组是否为空
        if (isEmpty()){
            throw new IllegalStateException();
        }
        //end为开区间，先往前移
        end = (end - 1 + size) % size;
        array[end] = null;
        count--;

        if (count > 0 && count <= (size / 4)){
            reSize(size/2);
        }
    }

    public int getFirst(){
        if (isEmpty()){
            throw new IllegalStateException();
        }

        return array[start];
    }

    public int getLast(){
        if (isEmpty()){
            throw new IllegalStateException();
        }
        return array[(end-1+size)%size];
    }

    //自动扩容辅助函数
    public void reSize(int newSize){
        //创建新数组
        Integer[] newArray = new Integer[newSize];
        //复制
        for (int i = 0; i < count; i++) {
            newArray[i] = array[(start + i) % size];
        }

        array = newArray;
        start = 0;
        end = count;
        size = newSize;
    }

    //判断是否为满
    public Boolean isFull(){
        return count == size;
    }

    public Boolean isEmpty(){
        if (count==0){
            return true;
        }else {
            return false;
        }
    }

    public static void main(String[] args) {
        CircularArray circularArray = new CircularArray(5);
        circularArray.addFirst(1);
        circularArray.addLast(2);
        circularArray.addLast(3);
        circularArray.removeFirst();
        circularArray.removeLast();
        circularArray.getFirst();
        for (Integer integer : circularArray.array) {
            System.out.println("integer = " + integer);
        }
    }
}
